<template>
  <div class="app-container">
    <el-form :inline="true" label-position="right" ref="queryRef" :model="params" label-width="200px" :rules="rules">
      <div class="form-inline">
        <el-row justify="center">
            <el-col :span="11">
                <el-form-item label="钻孔依托的项目：" class="form-item" prop="projectName">
                    <el-input v-model="params.projectName" placeholder="" clearable />
                </el-form-item>
            </el-col>
            <el-col :span="11">
                <el-form-item label="土动力试验参数：" class="form-item" prop="soilDynamic">
                    <el-select placeholder="请选择" class="form-select" v-model="params.soilDynamic">
                        <el-option v-for="item in soilDynamicOptions" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row justify="center">
            <el-col :span="11">
              <el-form-item label="孔位：" class="form-location">
                            <el-form-item label="经度" label-width="40px">
                                <el-form-item label-width="0px" prop="startHlLongitude">
                                    <el-input v-model="params.startHlLongitude" placeholder="请输入" class="el-form-longitude" clearable />
                                </el-form-item>
                                <span class="line" style="padding:0 3px;">--</span>
                                <el-form-item label-width="0px" prop="endHlLongitude">
                                    <el-input v-model="params.endHlLongitude" placeholder="请输入" class="el-form-longitude" clearable />
                                </el-form-item>
                            </el-form-item>
                              &emsp;
                            <el-form-item label="纬度" label-width="40px">
                                <el-form-item label-width="0px" prop="startHlLatitude">
                                    <el-input v-model="params.startHlLatitude" placeholder="请输入" class="el-form-longitude" clearable />
                                </el-form-item>
                                <span class="line" style="padding:0 3px;">--</span>
                                    <el-form-item label-width="0px" prop="endHlLatitude">
                                        <el-input v-model="params.endHlLatitude" placeholder="请输入" class="el-form-longitude" clearable />
                                    </el-form-item>
                            </el-form-item>
                          <!-- <el-form-item label="经度" label-width="40px" prop="hlLongitude">
                              <el-input v-model="params.hlLongitude" placeholder="" class="el-form-longitude" clearable />
                          </el-form-item>&emsp;
                          <el-form-item label="纬度" label-width="40px" prop="hlLatitude">
                              <el-input v-model="params.hlLatitude" placeholder="" class="el-form-latitude" clearable />
                          </el-form-item> -->
                      </el-form-item>
            </el-col>
            <el-col :span="11">
                <el-form-item label="剪切波实测值：" class="form-item" prop="measuredValues">
                    <el-select placeholder="请选择" class="form-select" v-model="params.measuredValues" clearable>
                        <el-option v-for="item in measuredValuesOptions" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row justify="center">
            <el-col :span="11">
                <el-form-item label="数据类别：" class="form-item" prop="dataType">
                    <el-select v-model="params.dataType" placeholder="请选择" class="form-select">
                        <el-option v-for="item in dataTypeOptions" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="11">
                <el-form-item label="场地类别：" class="form-item" prop="siteType">
                    <el-select v-model="params.siteType" placeholder="请选择" class="form-select">
                        <el-option v-for="item in siteTypeOptions" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row justify="end">
            <el-form-item class="bottom-button">
                <!-- <el-button type="primary" @click="onImportParms()">导入</el-button> -->
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button type="primary" @click="onRest">重置</el-button>
                <el-button type="primary" @click="onExport">导出</el-button>
            </el-form-item>
        </el-row>
      </div>
    </el-form>

    <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="列表展示" name="first">
        <div class="table-wrapper">
          <!-- @current-change="handleTableCurrentChange"  -->
          <el-table class="listTable" ref="multipleTableRef" border :data="tableData" style="width: 100%"
            @selection-change="handleSelectionChange" :cell-style="{ border: '1px solid #e5ebf7',}" :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none',}">
            :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
            <el-table-column prop="name" header-align="center" align="center" label="项目名称" width="200" show-overflow-tooltip />
            <el-table-column prop="projectName" header-align="center" align="left" label="钻孔依托的项目"
                width="290">
                <template #default="scope">
                    <el-button link type="text" size="small" @click.prevent="viewProject(scope.row)">
                        {{ scope.row.projectName }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="孔位" header-align="center" align="center">
                <el-table-column prop="hlLongitude" label="经度" header-align="center" align="center"
                    width="110" />
                <el-table-column prop="hlLatitude" label="纬度" header-align="center" align="center"
                    width="110" />
            </el-table-column>
            <el-table-column prop="boreholeNumber" header-align="center" align="center" label="钻孔编号" />
            <el-table-column prop="groundElevation" header-align="center" align="center" label="地面高程" />
            <el-table-column prop="drillingDepth" header-align="center" align="center" label="钻孔深度" />
            <el-table-column prop="y06Exist" header-align="center" align="center" label="土动力试验参数">
                <template #default="scope">
                    {{ scope.row.y06Exist === '1' ? '存在' : '不存在' }}
                </template>
            </el-table-column>
            <el-table-column prop="y08Exist" header-align="center" align="center" label="剪切波实测值">
                <template #default="scope">
                    {{ scope.row.y08Exist === '1' ? '存在' : '不存在' }}
                </template>
            </el-table-column>
            <el-table-column prop="fieldType" header-align="center" align="center" label="场地类别">
                <template #default="{ row }">
                    {{ mapSiteType[row.fieldType] || '' }}
                </template>
            </el-table-column>
            <el-table-column prop="dataType" header-align="center" align="center" label="数据类别" />
          </el-table>
          <div class="paging">
            <el-pagination background v-model:current-page="queryPagination.pageNo" :layout="layout"
              :page-size="queryPagination.pageSize" :total="queryPagination.total" @current-change="handleCurrentChange"
              @size-change="handleSizeChange" />
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="区域位置" name="second">
        <!--地图-->
        <AdminHoleResultQueryMap v-show="activeName=='second'" :dataList="mapDataList" ref="mapRefadminKW" @getAdminResultsHlByGeomText="getAdminResultsHlByGeomText" @mapLoading="mapLoading"></AdminHoleResultQueryMap>
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="dialogVisible" title="历史操作记录" width="30%">
      <div class="historyInfo" v-html="historyRecordContent"></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogVisible = false">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="adminHoleLocationManage">
//地图
import AdminHoleResultQueryMap from '@/map/earthquakeLevelResultManage/adminManage/holeLocation/map.vue';
import { downloadGet } from '@/utils/request'
import { ElMessage } from 'element-plus'
import { getXqhResultsHl, queryHistory } from "@/api/earthquakeLevelResultManage/provinceResultManage/provinceResultHoleLocationManage.js";
import { queryAdminHlByGeomText } from "@/api/earthquakeLevelResultManage/earthquakeLevelResultManage.js";
// 引入表单验证规则
import {
    validateLon, //验证经度
    validateLat, //验证纬度
} from "@/components/FormValidate";
// 引入store
import useDictStore from "@/store/modules/dict";
import {ref} from "vue";
const router = useRouter();
const { proxy } = getCurrentInstance()
// store对象
const dictStore = useDictStore();
// 场地类别map
let mapSiteType = dictStore.ArrayToMap(dictStore.siteTypeOptions);

const data = reactive({
  params: {
    projectName: "", //钻孔依托的项目
    startHlLongitude: "", //起始经度
    endHlLongitude: "", //结束经度
    startHlLatitude: "", //起始纬度
    endHlLatitude: "", //结束经度
    //hlLongitude: "",//孔位经度
    //hlLatitude: "",//孔位纬度
    dataType: "",//数据类别
    siteType: "",//场地类别
    soilDynamic: "", //土动力试验参数：
    measuredValues: '',//剪切波实测值：
  },
  rules: {
      startHlLongitude: [
          { message: "请输入开始经度", trigger: "blur" },
          {
              validator: validateLon,
              trigger: ["change", "blur"],
          },
      ],
      endHlLongitude: [
          { message: "请输入结束经度", trigger: "blur" },
          {
              validator: validateLon,
              trigger: ["change", "blur"],
          },
      ],
      startHlLatitude: [
          { message: "请输入开始纬度", trigger: "blur" },
          {
              validator: validateLat,
              trigger: ["change", "blur"],
          },
      ],
      endHlLatitude: [
          { message: "请输入结束纬度", trigger: "blur" },
          {
              validator: validateLat,
              trigger: ["change", "blur"],
          },
      ]
  },
  // 土动力实验参数
  soilDynamicOptions: dictStore.soilDynamicOptions || [],
  // 数据类别，候选值：安评成果库、区评成果库、小区划成果库，数据管理系统
  dataTypeOptions: dictStore.dataTypeOptions || [],
  // 场地类别，候选值：I1类场地、Ⅱ类场地、Ⅲ类场地、Ⅳ类场地、I0场地
  siteTypeOptions: dictStore.siteTypeOptions || [],
  // 剪切波实测值选项
  measuredValuesOptions: dictStore.measuredValuesOptions || [],
  //分页
  layout: " prev, pager, next, jumper, sizes, total",
  queryPagination: {
    pageNo: 1,
    pageSize: 10,
    total: 0,
  },
  //表格
  tableData: []
});
const {
  params,
  queryPagination,
  layout,
  rules,
  soilDynamicOptions,
  siteTypeOptions,
  measuredValuesOptions,
  dataTypeOptions,
  tableData
} = toRefs(data);
const activeName = ref("first");
const onRest = () => {
  proxy.resetForm("queryRef")
  queryPagination.value.pageNo = 1;
  proxy.$refs['mapRefadminKW'].clearadminKWMapQX();
  currentGemo.value=null;
  lastSearchParams.value=null;
  onSearch()
};
const handleSizeChange = (val) => {
  onSearch()
};
const handleCurrentChange = (val) => {
  onSearch()
};

const multipleTableRef = ref();
const multipleSelection = ref([]);
const curTableRow = ref(null);
//行政区
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  curTableRow.value = val;
};
onMounted(() => {
  onSearch()
})

// 查看跳转信息页面
const viewProject = (row) => {
  console.log(row.dataType,'llalla');
    if (row.pfId) {
        router.push({
            path: '/drillingInfoCompreQuery/drillHoleDisplay', query: {
                id: row.pfId, // row.projectId
                type: row.dataType
            }
        });
    } else {
        proxy.$modal.msgWarning('当前行数据编号为空!');
    }
}

//张平修改
const isRefesh = ref(true);
const handleClick = (tab, event) => {
  if(activeName.value=="second"&&isRefesh.value) {
    isRefesh.value=false;
    console.log(proxy.$refs['mapRefadminKW'],'===')
    proxy.$refs['mapRefadminKW'].switchTabadminKWMap();
  }else{
    queryPagination.value.pageNo = 1;
  }
  onSearch();
}

const lastSearchParams=ref({});
const currentGemo=ref();

const getListAndMapData = ()=>{
if(activeName.value=="second"){
  const queryMap = {
    ...lastSearchParams.value,
    geomText: currentGemo.value,
  }
  //管理员孔位信息地图圈选查询
  queryAdminHlByGeomText(queryMap).then((res) => {
    if (res.code === 200) {
      mapDataList.value = res.data.rows;
    }
  }).catch(err => {
    console.log(err);
    proxy.$modal.msgError('查询失败！');
  });
  }else{
  const query = {
    ...lastSearchParams.value,
    page: queryPagination.value.pageNo,
    rows: queryPagination.value.pageSize,
    geom:currentGemo.value
  }
  getXqhResultsHl(query).then((res) => {
    if (res.code === 200) {
      queryPagination.value.total = res.data.total;
      // proxy.$modal.msgSuccess("查询到"+res.data.total+"条孔位数据.");
      tableData.value = res.data.rows?res.data.rows:[];
    }
  }).catch(err => {
    queryPagination.value.total = 0;
    tableData.value = [];
    console.log(err);
  });
}  
};

//张平修改

//孔位信息表格
const onSearch = () => {
  lastSearchParams.value=JSON.parse(JSON.stringify(params.value));
  getListAndMapData();

  /*const query = {
    ...params.value,
    page: queryPagination.value.pageNo,
    rows: queryPagination.value.pageSize
  }
  getXqhResultsHl(query).then((res) => {
    if (res.code === 200) {
      queryPagination.value.total = res.data.total;
      tableData.value = [];
      const rows = res.data.rows;
      //循环遍历之前加上非空判断
      if (rows.length >= 0) {
        rows.forEach((item) => {
          tableData.value.push({
            originalDataId: item.originalDataId,
            projectId: item.projectId,
            projectName: item.projectName,
            longitude: item.longitude,
            latitude: item.latitude,
            administrativeRegion: item.administrativeRegion,
            subDate: item.subDate,
            reviewUnit: item.reviewUnit,
            undertaker: item.undertaker,
            sr: item.sr,
            registrant: item.registrant,
            createTime: item.createTime,
            registrationUnit: item.registrationUnit,
            status: item.status,
            model: item.model,
            approvalStatus: item.approvalStatus
          });
        });
      }
    }
  }).catch(err => {
    console.log(err);
  });*/
};

const praseStatus = (code) => {
  let codeStr = '无'
  switch (code) {
    case "0":
      codeStr = '无'
      break;
    case "1":
      codeStr = '待修改'
      break;
    case "2":
      codeStr = '已修改'
      break;
    case "3":
      codeStr = '待删除'
      break;
    case "4":
      codeStr = '已删除'
      break;
    default:
      break;
  }
  return codeStr
}

//审批状态选项
const approvalStatus = (code) => {
  let codeStr = '无'
  switch (code) {
    case "0":
      codeStr = '无'
      break;
    case "1":
      codeStr = '待审批'
      break;
    case "2":
      codeStr = '审批通过'
      break;
    case "3":
      codeStr = '审批不通过'
      break;
    default:
      break;
  }
  return codeStr
}

//项目信息删除
const onDelete = (row) => {
  console.log(row)
  router.push({ path: '/microzonationEvalutionResultsBank/microzonationEvaResCatRegister', query: { operate: 'delete', projectId: row.projectId } })
  // const params = {
  //   projectId: row.projectId,
  //   deleteReason: '测试'
  // }
  // ElMessageBox.confirm('此操作将删除数据, 是否继续?', '提示', {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消',
  //   type: 'warning'
  // }).then(() => {
  //   deleteSaResultsProject(params).then((res) => {
  //     console.log(res)
  //     if (res.data === '删除成功') {
  //       ElMessage({
  //         type: 'success',
  //         message: '删除成功!'
  //       });
  //       onSearch()
  //     }

  //   }).catch(err => {
  //     console.log(err);
  //     ElMessage({
  //       type: 'error',
  //       message: '删除失败!'
  //     });
  //   })

  // }).catch(() => {
  //   ElMessage({
  //     type: 'info',
  //     message: '已取消删除'
  //   });
  // });

}

//修改
const onModify = (row) => {
  router.push({ path: '/microzonationEvalutionResultsBank/microzonationEvaResCatRegister', query: { operate: 'modify', projectId: row.projectId } })
}
// 历史操作记录
const onHistoryRecord = (row) => {
  console.log(row, '55555555');
  dialogVisible.value = true
  const paramsp = {
    //projectId: row.projectId
    type:'2',
    id: row.logId
    // originalDataId: row.originalDataId
  }
  historyRecordContent.value = ""
  queryHistory(paramsp).then(res => {
    if (res.code === 200) {
      res.data.forEach(item => {
        historyRecordContent.value += `<span>${item.company}${item.userName}</span>于<span>${item.operationTime}</span>修改了<span>${item.tableName}${item.field}</span>信息，更改前：<span>${item.beforeUpdating}</span>，更改后：<span>${item.afterUpdate}</span><br/>`
      })
    }
  }).catch(err => {
    console.log(err)
  })
}


//导入
const onImport = () => {
  router.push({ path: '/microzonationEvalutionResultsBank/microzonationEvaResCatRegister' })
}

//导出
// const baseURL = import.meta.env.VITE_APP_BASE_API
const onExport = () => {
  // downloadGet('http://10.13.155.119:8081/fxfzdzqh/saResults/exportExcelSaResults', params, '文件.xls')
  proxy.download('/kzsfResults/exportExcel', params.value, '孔位信息.xls')
}

//地图传参--start
const mapDataList = ref([]);//地图圈选查询结果列表
//管理员孔位信息地图圈选查询
const getAdminResultsHlByGeomText = (geomText) => {
  if(geomText!=null && geomText!=""){
    currentGemo.value=geomText;
    getListAndMapData();

    /*const query = {
      ...params.value,
      geomText: geomText,
    }
    //管理员孔位信息地图圈选查询
    queryAdminHlByGeomText(query).then((res) => {
      if (res.code === 200) {
        mapDataList.value = res.data.rows;
        if(res.data.rows!=null && res.data.rows.length>0){
          let length = res.data.rows.length;
          proxy.$modal.msgSuccess("查询到"+length+"条数据.");
        }else{
          proxy.$modal.msgWarning('圈选范围无查询结果！');
        }
      }
    }).catch(err => {
      console.log(err);
      proxy.$modal.msgError('查询失败！');
    });*/
  }
};
//查询状态
const mapLoading = (bool) => {
  if(bool){
    proxy.$modal.loading("正在查询，请稍候...");
  }else{
    proxy.$modal.closeLoading();
  }
};
//地图传参--end
</script>

<style lang="scss" scoped>
.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.form-inline {
  :deep(.el-form-item__error) {
    z-index: 1;
  }

  .form-item {
    :deep(.el-form-item__content) {
      width: 300px;
    }

    .form-select {
      width: 300px;
    }

    .form-date {
      width: 130px;
    }
  }

  .form-location-p {
    margin-left: 138px;

    .el-form-longitude-p,
    .el-form-latitude-p {
      width: 105px;
    }
  }


  .form-location {
    .el-form-item {
      margin-right: 0;
    }

    .el-form-longitude,
    .el-form-latitude {
      width: 100px;
    }
  }
}

.paging {
  padding: 20px 10%;
  .el-pagination{
    justify-content: center;
  }
}
</style>

  